package com.qf.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 常肖飞先生
 * @version V1.0
 * @Project day41_2
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/11 17:33
 */
@WebServlet(name = "CounterServlet",urlPatterns = "/counter")
public class CounterServlet extends HttpServlet {
//    使用servletContext对象统计servlet被访问的次数
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext app = this.getServletContext();


        synchronized (this){
            //
            Integer count = (Integer)app.getAttribute("count");
            if(count == null){//第一次访问serlvet
                count = 1;
                app.setAttribute("count",count);
            }else{
                //第n次访问，在原有的基础上+1
                app.setAttribute("count",++count);
            }

            response.getWriter().println("count = " + count);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
